class Genre < ActiveRecord::Base
  #Relations
  belongs_to	:forum
  has_many	:artists_genres, :dependent => :destroy
  has_many	:editions_genres, :dependent => :destroy
  has_many	:genres_genres
  has_many	:images, :as => :photographable, :dependent => :destroy
  has_many	:reviews, :as => :reviewable
  has_many	:edits, :as => :editable, :order => "created_at DESC"
  has_many	:artists, :through => :artists_genres, :source => :artist
  has_many	:editions, :through => :editions_genres, :source => :edition

  #Self referential stuff
  has_and_belongs_to_many :parents, :class_name => "Genre",
                                    :join_table => "genres_genres",
                                    :foreign_key => "child_id",
                                    :association_foreign_key => "parent_id"
  has_and_belongs_to_many :children, :class_name => "Genre",
                                     :join_table => "genres_genres",
                                     :foreign_key => "parent_id",
                                     :association_foreign_key => "child_id"

  #Callbacks
  after_update :create_edit
  after_create :new_entry_edit
  before_save  :add_forum

  #override the to_string method to return the objects name
  def to_s
    return name
  end

  #
  def to_param
    "#{id}-#{name.parameterize}"
  end

  #
  def primary_image
    if images.empty?
      return nil
    else
      images.first.image
    end
  end

  private

  #
  #
  def add_forum
    if self.new_record?
      title = "Forum for " + self.name
      forum = Forum.new(:title => title)
      forum.save!
      self.forum_id = forum.id
    end
  end

  #
  #
  def new_entry_edit
      entry = Hash.new
      entry.store("created", [self.name])
      Edit.create_edit(entry, self)
  end

  #
  #
  def create_edit
    if self.changed?
      Edit.create_edit(self.changes, self)
    end
  end

end
